package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.core.collection.CollectionUtil;
import com.bzkj.basicinfo.domain.basic.BasicStoArea;
import com.bzkj.basicinfo.domain.basic.BasicStoAreaRules;
import com.bzkj.basicinfo.domain.ncc.StoArea;
import com.bzkj.basicinfo.domain.ncc.Warehouse;
import com.bzkj.basicinfo.mapper.StoAreaMapper;
import com.bzkj.basicinfo.mapper.StoUnitMapper;
import com.bzkj.basicinfo.mapper.WarehouseMapper;
import com.bzkj.basicinfo.service.ncc.StoAreaService;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: Admin
 * @Description: 库区服务实现类
 * 提供库区的业务逻辑处理，包括新增、更新、查询和删除库区
 */
@Service
public class StoAreaServiceImpl implements StoAreaService
{

    @Autowired
    private StoAreaMapper stoAreaMapper; // 注入库区数据访问层

    @Autowired
    private StoUnitMapper stoUnitMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addStoArea(StoArea stoArea)
    {
        //所属库区数据
        String areaId = stoArea.getStoAreaId();
        String stoId = stoArea.getStoId();
        //获取当前登录人信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        String userName = user.getUserName();
        //判断整零
        String formulationName = stoArea.getFormulationName();
        if (formulationName.contains("整")) {
            stoArea.setCsflag("1");
        } else if (formulationName.contains("零")) {
            stoArea.setCsflag("0");
        } else {
            stoArea.setCsflag("2");
        }
        //组装数据
        stoArea.setCreateBy(userName);
        stoArea.setCreateTime(new Date());
        stoArea.setStoId(stoId);
        stoArea.setStoAreaId(areaId);
        int i = stoAreaMapper.insertFormulationInfo(stoArea);
        if(i > 0){
            return AjaxResult.success("剂型："+ formulationName +"，新增成功");
        }else{
            return AjaxResult.error("剂型："+ formulationName +"，新增失败");
        }
    }

    @Transactional
    @Override
    public AjaxResult updateStoArea(StoArea stoArea) {
        LoginUser user = SecurityUtils.getLoginUser();
        String stoId = stoArea.getStoId();
        String stoAreaId = stoArea.getStoAreaId();
        // 查询仓库与库区信息
        Warehouse warehouse = warehouseMapper.selectWarehouseById(stoId);
        StoArea area = stoAreaMapper.selectStoAreaById(stoAreaId);
        if (warehouse == null || area == null) {
            return AjaxResult.error("仓库或库区不存在，无法更新。");
        }
        // 旧数据
        StoArea oldData = stoAreaMapper.selectFormulationById(stoArea.getId());
        if (oldData == null) {
            return AjaxResult.error("未找到对应的剂型信息。");
        }
        // 查询当前库区下的所有剂型
        List<StoArea> formulations = stoAreaMapper.selectFormulationByStoIdAndAreaId(stoId, stoAreaId);
        // 判重（仅当修改了对应字段才检查）
        if (CollectionUtil.isNotEmpty(formulations)) {
            for (StoArea f : formulations) {
                // 跳过自己
                if (f.getId().equals(stoArea.getId())) continue;
                // 判断剂型名称重复
                if (!Objects.equals(oldData.getFormulationName(), stoArea.getFormulationName()) &&
                        Objects.equals(f.getFormulationName(), stoArea.getFormulationName())) {
                    return AjaxResult.error(String.format("%s的%s已经存在剂型名称：%s。",
                            warehouse.getStoName(), area.getStoAreaName(), stoArea.getFormulationName()));
                }
                // 判断剂型编码重复
                if (!Objects.equals(oldData.getFormulationCode(), stoArea.getFormulationCode()) &&
                        Objects.equals(f.getFormulationCode(), stoArea.getFormulationCode())) {
                    return AjaxResult.error(String.format("%s的%s已经存在剂型编码：%s。",
                            warehouse.getStoName(), area.getStoAreaName(), stoArea.getFormulationCode()));
                }
            }
        }
        stoArea.setUpdateBy(user.getUsername());
        stoArea.setUpdateTime(DateUtils.getNowDate());
        stoAreaMapper.updateStoArea(stoArea);
        return AjaxResult.success("修改成功");
    }


    @Override
    public StoArea getStoAreaById(String stoAreaId)
    {
        return stoAreaMapper.selectStoAreaById(stoAreaId); // 根据 ID 查询库区
    }

    @Override
    public List<StoArea> getStoAreaById(List<String> stoAreaIds) {
        return stoAreaMapper.selectStoAreaByIds(stoAreaIds);
    }

    @Override
    public List<StoArea> getAllStoAreas(StoArea stoArea)
    {
        return stoAreaMapper.selectAllStoAreas(); // 查询所有库区
    }

    @Override
    public List<BasicStoArea> getStoAreasByWarehouseId(String warehouseId)
    {
        return stoAreaMapper.selectStoAreasByWarehouseId(warehouseId); // 根据仓库 ID 查询库区
    }

    @Override
    public int deleteFormulation(String id)
    {
        return stoAreaMapper.deleteFormulation(id); // 删除库区
    }

    @Override
    public boolean hasUnits(String stoAreaId)
    {
        // 检查库区下的货位数量
        return stoUnitMapper.selectStoUnitsByAreaId(stoAreaId).size() > 0;
    }

    @Override
    public AjaxResult getBasicStoStock()
    {
        return AjaxResult.success(warehouseMapper.getBasicStoStock());
    }

    @Override
    public AjaxResult getAddStoUnitById(String sto_id)
    {
        List<HashMap> addStoUnitById = stoAreaMapper.getAddStoUnitById(sto_id);
        return AjaxResult.success(addStoUnitById);
    }

    @Override
    public List<HashMap<String, Object>> queryStoAreaHouse(String sto_code, String sto_area_code)
    {
        return stoAreaMapper.queryStoAreaHouse(sto_code, sto_area_code);
    }


    @Override
    public AjaxResult getAllAreaRules(String areaId) {
        List<BasicStoAreaRules> areaRules = stoAreaMapper.selectAreaRules(areaId);
        return AjaxResult.success(CollectionUtil.isEmpty(areaRules)? new ArrayList<>():areaRules);
    }

    @Override
    public AjaxResult addAreaRules(StoArea stoArea) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        String userName = user.getUserName();
        //删除旧数据
        int i = stoAreaMapper.deleteStoAreaRules(stoArea.getStoAreaId());
        if(i<0){
            return AjaxResult.error("保存失败");
        }
        List<String> typeList = stoArea.getCodeList();
        int size = typeList.size();
        typeList.forEach(e->{
            //去规则表中添加数据
            Map<String, Object> params = new HashMap<>();
            params.put("sto_area_id", stoArea.getStoAreaId());
            params.put("stu_class_id", e);
            params.put("createTime", new Date());
            params.put("creator", userName);
            params.put("def5",size);
            stoAreaMapper.insertStockMap(params);
        });
        return AjaxResult.success();
    }

    @Override
    public AjaxResult delAreaRules(String id) {
        int i = stoAreaMapper.deleteAreaRulesById(id);
        if(i>0){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    public String getTwoId()
    {
        Long aLong = stoAreaMapper.queryBigNumber();
        if(aLong == null) {
            return "2000000000";
        } else {
            aLong = aLong + 1;
            return aLong + "";
        }
    }
}
